#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : micah
# @time    : 2023/11/14 23:29
# @function: the script is used to do something.
# @version :


import socket
import re

# 获取到网页资源地址
urls = ['https://pic.netbian.com/uploads/allimg/220211/004115-1644511275bc26.jpg',
        'https://pic.netbian.com/uploads/allimg/220215/233510-16449393101c46.jpg',
        'https://pic.netbian.com/uploads/allimg/211120/005250-1637340770807b.jpg'
        ]


for url in urls:
    # 创建套接字  用套接字实现进程通信
    client = socket.socket()
    # https：443需要安全套接字
    # 创建连接，保障兼容性的问题，会开设80 端口
    client.connect(('pic.netbian.com', 80))

    # 构造http请求，获取网站服务器中的图片数据
    http_res = 'GET ' + url + ' HTTP/1.1\r\nHost:pic.netbian.com\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36\r\nConnection: close\r\n\r\n'
    # 发送请求获取响应数据  socket中的send方法不能发送字符串，send方法只能发字节
    client.send(http_res.encode())

    # 发送成功后服务器返回信息
    result = b''
    data = client.recv(1024)  # 指定当前最大接收的最大字节数
    # print(data)

    # 循环接收图片数据
    while data:
        result += data
        data = client.recv(1024)
    # print(result)

    # 提取数据信息
    images = re.findall(b'\r\n\r\n(.*)', result, re.S)  # 获取特殊字符
    # print(images)
    # 保存数据
    name = url.split('/')[-1]
    with open(name, 'wb') as f:
        f.write(images[0])
